import { Form, Select, Card, Button, Upload, Icon } from 'antd';
import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import { FormComponentProps } from 'antd/es/form';
import { StateType } from '../../model';
import { singlePageFormLayout, formItemLayout } from '@/common/layout/form';
import { ProductAttributeCategoryModelState } from '@/models/productAttributeCategory';
import { ProductAttributeCategory } from '../../../../../models/productAttributeCategory';
import { ProductAttribute } from '@/models/productAttribute';
import { ProductAttributeModelState } from '../../../../../models/productAttribute';
import SpecFormItem from './components/SpecFormItem';
import ParamFormItem from './components/ParamFormItem';
import { Loading } from '@/models/connect';
import { router } from 'umi';

const { Option } = Select;

interface Step3Props extends FormComponentProps {
  data?: StateType['formData'];
  categories: ProductAttributeCategory[];
  attributes: ProductAttribute[];
  dispatch: Dispatch<any>;
  selectLoading?: boolean;
  submitLoading?: boolean;
}

const Step3: React.FC<Step3Props> = props => {
  const { data, dispatch, form, categories, attributes, selectLoading, submitLoading } = props;
  const { getFieldDecorator, validateFields, getFieldsValue } = form;
  if (!data) {
    return null;
  }
  const { productAttributeCategoryId } = data;
  const onSelectChange = (value: number) => {
    dispatch({
      type: 'productAttribute/query',
      payload: {
        productAttributeCategoryId: value,
      },
    });
  };
  const onPrev = () => {
    if (dispatch) {
      const values = getFieldsValue();
      dispatch({
        type: 'addProduct/saveStepFormData',
        payload: {
          ...data,
          ...values,
        },
      });
      dispatch({
        type: 'addProduct/saveCurrentStep',
        payload: 'info',
      });
    }
  };
  const onValidateForm = (e: React.FormEvent) => {
    e.preventDefault();
    validateFields((err, values) => {
      if (!err && dispatch) {
        dispatch({
          type: 'addProduct/saveStepFormData',
          payload: {
            ...data,
            ...values,
          },
        });
        dispatch({
          type: 'addProduct/submitStepForm',
          payload: {
            ...data,
            ...values,
          },
          callback: () => {
            router.push({
              pathname: '/product/list',
            });
          },
        });
      }
    });
  };
  const normFile = (e: { fileList: any }) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };
  const categoryOptions = categories.map(item => (
    <Option key={item.id} value={item.id}>
      {item.name}
    </Option>
  ));
  const specifications = (attributes || []).filter(item => item.type === 0);
  const parameters = (attributes || []).filter(item => item.type === 1);
  return (
    <Form layout="horizontal" style={singlePageFormLayout}>
      <Form.Item {...formItemLayout} label="属性分类">
        {getFieldDecorator<ProductAttribute>('productAttributeCategoryId', {
          initialValue: productAttributeCategoryId,
        })(
          <Select placeholder="请选择" onChange={onSelectChange} loading={selectLoading}>
            {categoryOptions}
          </Select>,
        )}
      </Form.Item>
      <Form.Item {...formItemLayout} label="商品规格">
        <Card bodyStyle={{ background: '#F8F9FC' }}>
          {specifications.map(outer => (
            <Form.Item {...formItemLayout} key={outer.id} label={outer.name}>
              {getFieldDecorator(`#${outer.id!.toString()}`, {
                initialValue: data[`#${outer.id!.toString()}`],
              })(<SpecFormItem options={outer.inputList} />)}
            </Form.Item>
          ))}
        </Card>
      </Form.Item>
      <Form.Item {...formItemLayout} label="商品参数">
        <Card bodyStyle={{ background: '#F8F9FC' }}>
          {parameters.map(outer => (
            <Form.Item {...formItemLayout} key={outer.id} label={outer.name}>
              {getFieldDecorator(`#${outer.id!.toString()}`, {
                initialValue: data[`#${outer.id!.toString()}`],
              })(<ParamFormItem options={outer.inputList} />)}
            </Form.Item>
          ))}
        </Card>
      </Form.Item>
      <Form.Item {...formItemLayout} label="商品相册">
        {getFieldDecorator('albumPics', {
          valuePropName: 'fileList',
          getValueFromEvent: normFile,
          initialValue: data.pic,
          rules: [
            {
              required: true,
              message: '请选择一张商品图片',
            },
          ],
        })(
          <Upload listType="picture-card">
            <div>
              <Icon type="plus" style={{ fontSize: '28px' }} />
            </div>
          </Upload>,
        )}
      </Form.Item>
      <Form.Item
        style={{ marginBottom: 8 }}
        wrapperCol={{
          xs: { span: 24, offset: 0 },
          sm: {
            span: formItemLayout.wrapperCol.span,
            offset: formItemLayout.labelCol.span,
          },
        }}
        label=""
      >
        <Button onClick={onPrev}>上一步，填写商品信息</Button>
        <Button
          type="primary"
          onClick={onValidateForm}
          loading={submitLoading}
          style={{ marginLeft: 8 }}
        >
          完成，提交商品
        </Button>
      </Form.Item>
    </Form>
  );
};

export default connect(
  ({
    addProduct,
    productAttributeCategory,
    productAttribute,
    loading,
  }: {
    addProduct: StateType;
    productAttributeCategory: ProductAttributeCategoryModelState;
    productAttribute: ProductAttributeModelState;
    loading: Loading;
  }) => ({
    data: addProduct.formData,
    categories: productAttributeCategory.categories,
    attributes: productAttribute.attributes,
    selectLoading: loading.models.productAttributeCategory,
    submitLoading: loading.models.addProduct,
  }),
)(Form.create<Step3Props>()(Step3));
